import os
import sys
import base64
import traceback
import uuid
import time
import threading
from typing import Dict, Any, Tuple, Optional
from flask import Flask, request, jsonify
from flask_cors import CORS
import joblib

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from prepare_ali_data import (
    calculate_experience_score,
    calculate_education_score,
    calculate_compensation_score,
    calculate_responsibility_score,
    determine_location_tier,
    determine_tech_level,
    determine_role_type,
    determine_school_level
)
from salary_analyzer import SalaryAnalyzer
from resume_parser import extract_text_from_file, parse_resume_info
from comment_generator import CommentGenerator  

app = Flask(__name__)
CORS(app)  # 启用跨域支持

# 配置文件上传
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 限制文件大小为16MB

model = None
salary_analyzer = None
comment_generator = None  

def load_model():
    """加载训练好的模型和薪资分析"""
    global model, salary_analyzer, comment_generator  
    try:
        model_path = 'model_simple.joblib'
        if os.path.exists(model_path):
            model = joblib.load(model_path)
            print("模型加载成功")
        else:
            print(f"模型文件不存在: {model_path}")
            return False
            
        try:
            salary_analyzer = SalaryAnalyzer()
            print("薪资分析加载成功")
        except Exception as e:
            print(f"薪资分析加载失败: {e}")
            salary_analyzer = None
            
        try:
            comment_generator = CommentGenerator() 
            print("评价生成器加载成功")
        except Exception as e:
            print(f"评价生成器加载失败: {e}")
            comment_generator = None
            
        return True
    except Exception as e:
        print(f"模型加载失败: {str(e)}")
        return False

def validate_request_data(data: Dict[str, Any]) -> Tuple[bool, list]:
    """验证请求参数"""
    errors = []
    
    # 必填
    required_fields = {
        'year_of_experience': '总工作年限',
        'degree': '最高学历',
        'bachelor_school': '本科学校',
        'job_type': '职位类型',
        'location': '工作城市',
        'annual_salary': '年薪'
    }
    
    for field, desc in required_fields.items():
        if field not in data or data[field] is None:
            errors.append({
                'field': field,
                'message': f'{desc}为必填项'
            })
    
    if errors:
        return False, errors
    
    # 数值类型
    numeric_fields = {
        'year_of_experience': ('总工作年限', 0, 20),
        'annual_salary': ('年薪', 36000, 1200000)
    }
    
    for field, (desc, min_val, max_val) in numeric_fields.items():
        if field in data:
            try:
                value = float(data[field])
                if not (min_val <= value <= max_val):
                    errors.append({
                        'field': field,
                        'message': f'{desc}应在{min_val}-{max_val}范围内'
                    })
            except (ValueError, TypeError):
                errors.append({
                    'field': field,
                    'message': f'{desc}必须是数字'
                })
    
    # 枚举值
    enum_fields = {
        'degree': ['专科', '本科', '硕士', '博士'],
        'job_type': ['开发', '产品经理', '主管', '设计']
    }
    
    for field, valid_values in enum_fields.items():
        if field in data and data[field] not in valid_values:
            errors.append({
                'field': field,
                'message': f'{field}必须是以下值之一: {", ".join(valid_values)}'
            })
    
    # 字符串长度
    string_fields = {
        'bachelor_school': ('本科学校', 1, 50),
        'location': ('工作城市', 1, 20)
    }
    
    for field, (desc, min_len, max_len) in string_fields.items():
        if field in data:
            value = str(data[field]).strip()
            if not (min_len <= len(value) <= max_len):
                errors.append({
                    'field': field,
                    'message': f'{desc}长度应在{min_len}-{max_len}字符之间'
                })
    
    return len(errors) == 0, errors

def prepare_prediction_features(data: Dict[str, Any]) -> Dict[str, Any]:
    """准备预测所需的特征"""
    
    job_type_mapping = {
        '开发': '开发工程师',
        '设计': '设计师', 
        '主管': '架构师',
        '产品经理': '技术经理'
    }

    job_type_to_role = {
        '开发工程师': 'IC',
        '设计师': 'IC', 
        '架构师': '专家',
        '技术经理': '管理'
    }
    
    # 基础特征转换
    user_input = {
        'year_of_experience': float(data['year_of_experience']),
        # 如果没有提供year_in_company，则默认等于year_of_experience
        'year_in_company': float(data.get('year_in_company', data['year_of_experience'])),
        'degree': data['degree'],
        'bachelor_school': data['bachelor_school'],
        'advanced_school': data.get('advanced_school', '其他'),
        'title': job_type_mapping[data['job_type']],
        'location': data['location'],
        'base_monthly_comp': float(data['annual_salary']) / 12, 
        'bonus_comp': 0,  # 年薪已包含奖金，不再单独计算
        'stock_comp': 0, 
        'total_comp': float(data['annual_salary']) 
    }
    
    # 计算特征评分
    features = {
        'experience_score': calculate_experience_score(
            user_input['year_of_experience'],
            user_input['year_in_company']
        ),
        'education_score': calculate_education_score(
            user_input['degree'],
            determine_school_level(
                user_input['bachelor_school'],
                user_input['advanced_school']
            )
        ),
        'technical_score': 0,
        'workload_score': 70,  
        'compensation_score': calculate_compensation_score(
            user_input['total_comp'],  
            user_input['location'],
            user_input['base_monthly_comp'],  
            user_input['bonus_comp'],  
            0
        ),
        'responsibility_score': calculate_responsibility_score(
            user_input['title'],
            '技术部',
            user_input['total_comp'] 
        ),
        'location_tier': determine_location_tier(user_input['location']),
        'tech_level': determine_tech_level(
            user_input['title'],
            user_input['year_of_experience']
        ),
        'role_type': job_type_to_role[user_input['title']],
        'business_domain': '其他'  # 固定为'其他'
    }
    
    return features
    
@app.route('/api/v1/predict', methods=['POST'])
def predict_level():
    """职级预测API"""
    try:
        if model is None:
            return jsonify({
                'code': 503,
                'message': '模型未加载'
            }), 503
        
        if not request.is_json:
            return jsonify({
                'code': 400,
                'message': '请求必须是JSON格式'
            }), 400
        
        data = request.get_json()
        
        is_valid, errors = validate_request_data(data)
        if not is_valid:
            return jsonify({
                'code': 400,
                'message': '参数错误',
                'errors': errors
            }), 400
        
        # 准备预测
        features = prepare_prediction_features(data) 
        predicted_level, confidence, probabilities = model.predict_level(features)
        
        salary_analysis_result = None
        if salary_analyzer is not None:
            try:
                analysis = salary_analyzer.analyze_prediction(predicted_level)
                salary_analysis_result = salary_analyzer.format_analysis_result(analysis)
                print(f"薪资分析完成: {predicted_level}")
            except Exception as e:
                print(f"薪资分析失败: {e}")
                salary_analysis_result = None
        
        # 是否触发保底机制
        is_fallback = False
        fallback_reason = None
        
        total_score = (
            features['experience_score'] + 
            features['education_score'] + 
            features['compensation_score'] + 
            features['responsibility_score']
        )
        
        if predicted_level == 'P4':
            conditions = []
            if total_score < 120:  
                conditions.append('总分过低')
            if features['experience_score'] < 20:  
                conditions.append('经验不足')
            if features['compensation_score'] < 20:  
                conditions.append('薪资较低')
            if features['responsibility_score'] <= 45: 
                conditions.append('责任评分较低')
            if features['tech_level'] == '初级':
                conditions.append('技术等级为初级')
            if len(conditions) >= 4:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P4保底机制: {", ".join(conditions)}'
        
        elif predicted_level == 'P9':
            conditions = []
            if total_score > 290:  
                conditions.append('总分很高')
            if features['experience_score'] > 85:  
                conditions.append('经验丰富')
            if features['compensation_score'] > 60:  
                conditions.append('薪资很高')
            if features['responsibility_score'] > 70:  
                conditions.append('责任评分很高')
            if features['tech_level'] == '专家' or features['role_type'] == '管理':
                conditions.append('技术等级为专家或角色类型为管理')
            if len(conditions) >= 5:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P9保底机制: {", ".join(conditions)}'

        response_data = {
            'predicted_level': predicted_level,
            'confidence': round(confidence, 4),
            'probabilities': {k: round(v, 4) for k, v in probabilities.items()},
            'feature_scores': {
                'experience_score': round(features['experience_score'], 2),
                'education_score': round(features['education_score'], 2),
                'compensation_score': round(features['compensation_score'], 2),
                'responsibility_score': round(features['responsibility_score'], 2)
            },
            'city_tier': features['location_tier'],
            'is_fallback': is_fallback,
            'fallback_reason': fallback_reason
        }
    
        if salary_analysis_result is not None:
            response_data['salary_analysis'] = salary_analysis_result['salary_analysis']
            response_data['equivalent_levels'] = salary_analysis_result['equivalent_levels']
        

        response_data = add_comment_to_response(response_data)
        
        print(f"预测成功: {predicted_level}, 置信度: {confidence:.4f}")
        
        return jsonify({
            'code': 200,
            'message': '预测成功',
            'data': response_data
        })
        
    except Exception as e:
        error_msg = str(e)
        print(f"预测失败: {error_msg}")
        
        return jsonify({
            'code': 500,
            'message': '服务器内部错误',
            'error': error_msg
        }), 500

@app.route('/api/v1/predict_from_resume', methods=['POST'])
def predict_from_resume():
    """从简历文件预测职级API"""
    print("[DEBUG] 收到简历预测请求")
    try:
        if model is None:
            print("[ERROR] 模型未加载")
            return jsonify({
                'code': 503,
                'message': '模型未加载'
            }), 503
        
        # 检查是否是base64上传
        if request.is_json:
            print("[DEBUG] 检测到JSON请求（Base64上传）")
            data = request.get_json()
            if 'resume_base64' in data and 'filename' in data:
                try:
                    file_content = base64.b64decode(data['resume_base64'])
                    filename = data['filename']
                    print(f"[DEBUG] Base64解码完成，文件名: {filename}, 大小: {len(file_content)} bytes")
                except Exception as e:
                    print(f"[ERROR] Base64解码失败: {str(e)}")
                    return jsonify({
                        'code': 400,
                        'message': f'Base64解码失败: {str(e)}'
                    }), 400
            else:
                if 'resume' not in request.files:
                    print("[ERROR] 未找到简历文件")
                    return jsonify({
                        'code': 400,
                        'message': '请上传简历文件或提供base64编码的简历'
                    }), 400
                
                file = request.files['resume']
                
                if file.filename == '' or file.filename is None:
                    print("[ERROR] 文件名为空")
                    return jsonify({
                        'code': 400,
                        'message': '请选择要上传的文件'
                    }), 400
                
                filename = file.filename or ''
                
                file_content = file.read()
                print(f"[DEBUG] 文件读取完成，文件名: {filename}, 大小: {len(file_content)} bytes")
        else:
            print("[DEBUG] 检测到文件上传请求")
            if 'resume' not in request.files:
                print("[ERROR] 未找到简历文件")
                return jsonify({
                    'code': 400,
                    'message': '请上传简历文件或提供base64编码的简历'
                }), 400
            
            file = request.files['resume']
            
            if file.filename == '' or file.filename is None:
                print("[ERROR] 文件名为空")
                return jsonify({
                    'code': 400,
                    'message': '请选择要上传的文件'
                }), 400
            
            filename = file.filename or ''

            file_content = file.read()
            print(f"[DEBUG] 文件读取完成，文件名: {filename}, 大小: {len(file_content)} bytes")
        

        allowed_extensions = {'.pdf', '.docx', '.doc'}
        if not any(filename.lower().endswith(ext) for ext in allowed_extensions):
            print(f"[ERROR] 不支持的文件格式: {filename}")
            return jsonify({
                'code': 400,
                'message': '只支持PDF和Word文档格式'
            }), 400
        
        try:
            resume_text = extract_text_from_file(file_content, filename)
            print(f"[DEBUG] 文本提取完成，字符数: {len(resume_text)}")
        except Exception as e:
            print(f"[ERROR] 文件解析失败: {str(e)}")
            return jsonify({
                'code': 400,
                'message': f'文件解析失败: {str(e)}'
            }), 400
        
        try:
            user_info = parse_resume_info(resume_text)
            print(f"[DEBUG] 大模型API调用完成，解析结果: {user_info}")
        except Exception as e:
            print(f"[ERROR] 简历信息提取失败: {str(e)}")
            traceback.print_exc()
            return jsonify({
                'code': 500,
                'message': f'简历信息提取失败: {str(e)}'
            }), 500
        
        features = prepare_prediction_features(user_info)
        print(f"[DEBUG] 预测特征准备完成: {features}")
        
        predicted_level, confidence, probabilities = model.predict_level(features)
        print(f"[DEBUG] 模型预测完成，预测职级: {predicted_level}, 置信度: {confidence}")
        
        salary_analysis_result = None
        if salary_analyzer is not None:
            try:
                analysis = salary_analyzer.analyze_prediction(predicted_level)
                salary_analysis_result = salary_analyzer.format_analysis_result(analysis)
                print(f"[DEBUG] 薪资分析完成: {predicted_level}")
            except Exception as e:
                print(f"[ERROR] 薪资分析失败: {e}")
                traceback.print_exc()
                salary_analysis_result = None
        
        # 是否触发保底机制
        is_fallback = False
        fallback_reason = None
        
        total_score = (
            features['experience_score'] + 
            features['education_score'] + 
            features['compensation_score'] + 
            features['responsibility_score']
        )
        
        if predicted_level == 'P4':
            conditions = []
            if total_score < 120:  
                conditions.append('总分过低')
            if features['experience_score'] < 20:  
                conditions.append('经验不足')
            if features['compensation_score'] < 20:  
                conditions.append('薪资较低')
            if features['responsibility_score'] <= 45:  
                conditions.append('责任评分较低')
            if features['tech_level'] == '初级':
                conditions.append('技术等级为初级')
            if len(conditions) >= 4:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P4保底机制: {", ".join(conditions)}'
        
        elif predicted_level == 'P9':
            conditions = []
            if total_score > 290:  
                conditions.append('总分很高')
            if features['experience_score'] > 85:  
                conditions.append('经验丰富')
            if features['compensation_score'] > 60:  
                conditions.append('薪资很高')
            if features['responsibility_score'] > 70:  
                conditions.append('责任评分很高')
            if features['tech_level'] == '专家' or features['role_type'] == '管理':
                conditions.append('技术等级为专家或角色类型为管理')
            if len(conditions) >= 5:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P9保底机制: {", ".join(conditions)}'
        
        response_data = {
            'predicted_level': predicted_level,
            'confidence': round(confidence, 4),
            'probabilities': {k: round(v, 4) for k, v in probabilities.items()},
            'feature_scores': {
                'experience_score': round(features['experience_score'], 2),
                'education_score': round(features['education_score'], 2),
                'compensation_score': round(features['compensation_score'], 2),
                'responsibility_score': round(features['responsibility_score'], 2)
            },
            'city_tier': features['location_tier'],
            'is_fallback': is_fallback,
            'fallback_reason': fallback_reason,
            'extracted_info': user_info  # 返回从简历中提取的信息
        }
    
        if salary_analysis_result is not None:
            response_data['salary_analysis'] = salary_analysis_result['salary_analysis']
            response_data['equivalent_levels'] = salary_analysis_result['equivalent_levels']
        

        response_data = add_comment_to_response(response_data)
        
        print(f"从简历预测成功: {predicted_level}, 置信度: {confidence:.4f}")
        
        return jsonify({
            'code': 200,
            'message': '预测成功',
            'data': response_data
        })
        
    except Exception as e:
        error_msg = str(e)
        print(f"从简历预测失败: {error_msg}")
        
        return jsonify({
            'code': 500,
            'message': '服务器内部错误',
            'error': error_msg
        }), 500

# 添加任务状态存储
processing_tasks = {}

def process_resume_task(task_id, file_content, filename):
    """异步处理简历任务"""
    print(f"[异步处理] 开始处理任务 {task_id}")
    processing_tasks[task_id] = {
        'status': 'processing',
        'result': None,
        'error': None,
        'start_time': time.time()
    }
    
    try:
        resume_text = extract_text_from_file(file_content, filename)
        print(f"[异步处理] 文本提取完成，字符数: {len(resume_text)}")
        
        user_info = parse_resume_info(resume_text)
        print(f"[异步处理] 大模型API调用完成，解析结果: {user_info}")

        features = prepare_prediction_features(user_info)
        print(f"[异步处理] 预测特征准备完成")
        
        if model is None:
            raise Exception("模型未加载")
        predicted_level, confidence, probabilities = model.predict_level(features)
        print(f"[异步处理] 模型预测完成，预测职级: {predicted_level}, 置信度: {confidence}")
        
        salary_analysis_result = None
        if salary_analyzer is not None:
            try:
                analysis = salary_analyzer.analyze_prediction(predicted_level)
                salary_analysis_result = salary_analyzer.format_analysis_result(analysis)
                print(f"[异步处理] 薪资分析完成: {predicted_level}")
            except Exception as e:
                print(f"[异步处理] 薪资分析失败: {e}")
                traceback.print_exc()
                salary_analysis_result = None
        
        # 是否触发保底机制
        is_fallback = False
        fallback_reason = None
        
        total_score = (
            features['experience_score'] + 
            features['education_score'] + 
            features['compensation_score'] + 
            features['responsibility_score']
        )
        
        if predicted_level == 'P4':
            conditions = []
            if total_score < 120:  
                conditions.append('总分过低')
            if features['experience_score'] < 20:  
                conditions.append('经验不足')
            if features['compensation_score'] < 20:  
                conditions.append('薪资较低')
            if features['responsibility_score'] <= 45:  
                conditions.append('责任评分较低')
            if features['tech_level'] == '初级':
                conditions.append('技术等级为初级')
            if len(conditions) >= 4:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P4保底机制: {", ".join(conditions)}'
        
        elif predicted_level == 'P9':
            conditions = []
            if total_score > 290:  
                conditions.append('总分很高')
            if features['experience_score'] > 85:
                conditions.append('经验丰富')
            if features['compensation_score'] > 60: 
                conditions.append('薪资很高')
            if features['responsibility_score'] > 70: 
                conditions.append('责任评分很高')
            if features['tech_level'] == '专家' or features['role_type'] == '管理':
                conditions.append('技术等级为专家或角色类型为管理')
            if len(conditions) >= 5:  # 需要满足更多条件
                is_fallback = True
                fallback_reason = f'触发P9保底机制: {", ".join(conditions)}'
        
        response_data = {
            'predicted_level': predicted_level,
            'confidence': round(confidence, 4),
            'probabilities': {k: round(v, 4) for k, v in probabilities.items()},
            'feature_scores': {
                'experience_score': round(features['experience_score'], 2),
                'education_score': round(features['education_score'], 2),
                'compensation_score': round(features['compensation_score'], 2),
                'responsibility_score': round(features['responsibility_score'], 2)
            },
            'city_tier': features['location_tier'],
            'is_fallback': is_fallback,
            'fallback_reason': fallback_reason,
            'extracted_info': user_info
        }
    
        if salary_analysis_result is not None:
            response_data['salary_analysis'] = salary_analysis_result['salary_analysis']
            response_data['equivalent_levels'] = salary_analysis_result['equivalent_levels']
        

        response_data = add_comment_to_response(response_data)
        
        print(f"[异步处理] 任务 {task_id} 处理成功")
        processing_tasks[task_id] = {
            'status': 'completed',
            'result': response_data,
            'error': None,
            'start_time': processing_tasks[task_id]['start_time'],
            'end_time': time.time()
        }
        
    except Exception as e:
        error_msg = str(e)
        print(f"[异步处理] 任务 {task_id} 处理失败: {error_msg}")
        traceback.print_exc()
        processing_tasks[task_id] = {
            'status': 'failed',
            'result': None,
            'error': error_msg,
            'start_time': processing_tasks[task_id]['start_time'],
            'end_time': time.time()
        }

@app.route('/api/v1/predict_from_resume_async', methods=['POST'])
def predict_from_resume_async():
    """异步从简历文件预测职级API"""
    print("[异步API] 收到简历预测请求")
    try:
        if model is None:
            print("[异步API] 模型未加载")
            return jsonify({
                'code': 503,
                'message': '模型未加载'
            }), 503
        
        # 生成任务ID
        task_id = str(uuid.uuid4())
        print(f"[异步API] 生成任务ID: {task_id}")
        
        # 检查是否是base64上传
        if request.is_json:
            print("[异步API] 检测到JSON请求（Base64上传）")
            data = request.get_json()
            if 'resume_base64' in data and 'filename' in data:
                try:
                    file_content = base64.b64decode(data['resume_base64'])
                    filename = data['filename']
                    print(f"[异步API] Base64解码完成，文件名: {filename}, 大小: {len(file_content)} bytes")
                except Exception as e:
                    print(f"[异步API] Base64解码失败: {str(e)}")
                    return jsonify({
                        'code': 400,
                        'message': f'Base64解码失败: {str(e)}'
                    }), 400
            else:

                if 'resume' not in request.files:
                    print("[异步API] 未找到简历文件")
                    return jsonify({
                        'code': 400,
                        'message': '请上传简历文件或提供base64编码的简历'
                    }), 400
                
                file = request.files['resume']
                
                if file.filename == '' or file.filename is None:
                    print("[异步API] 文件名为空")
                    return jsonify({
                        'code': 400,
                        'message': '请选择要上传的文件'
                    }), 400
                
                filename = file.filename or ''
                
                file_content = file.read()
                print(f"[异步API] 文件读取完成，文件名: {filename}, 大小: {len(file_content)} bytes")
        else:
            print("[异步API] 检测到文件上传请求")
            if 'resume' not in request.files:
                print("[异步API] 未找到简历文件")
                return jsonify({
                    'code': 400,
                    'message': '请上传简历文件或提供base64编码的简历'
                }), 400
            
            file = request.files['resume']
            
            if file.filename == '' or file.filename is None:
                print("[异步API] 文件名为空")
                return jsonify({
                    'code': 400,
                    'message': '请选择要上传的文件'
                }), 400
            
            filename = file.filename or ''
            
            file_content = file.read()
            print(f"[异步API] 文件读取完成，文件名: {filename}, 大小: {len(file_content)} bytes")
        
        allowed_extensions = {'.pdf', '.docx', '.doc'}
        if not any(filename.lower().endswith(ext) for ext in allowed_extensions):
            print(f"[异步API] 不支持的文件格式: {filename}")
            return jsonify({
                'code': 400,
                'message': '只支持PDF和Word文档格式'
            }), 400
        
        # 启动异步处理任务
        print(f"[异步API] 启动异步处理任务 {task_id}")
        thread = threading.Thread(target=process_resume_task, args=(task_id, file_content, filename))
        thread.start()
        
        # 返回任务ID
        return jsonify({
            'code': 202,
            'message': '任务已接受，正在处理中',
            'data': {
                'task_id': task_id
            }
        }), 202
        
    except Exception as e:
        error_msg = str(e)
        print(f"[异步API] 处理请求失败: {error_msg}")
        traceback.print_exc()
        return jsonify({
            'code': 500,
            'message': '服务器内部错误',
            'error': error_msg
        }), 500

@app.route('/api/v1/predict_from_resume_status/<task_id>', methods=['GET'])
def get_predict_status(task_id):
    """获取简历预测任务状态"""
    print(f"[状态API] 查询任务 {task_id} 状态")
    
    if task_id not in processing_tasks:
        return jsonify({
            'code': 404,
            'message': '任务不存在'
        }), 404
    
    task_info = processing_tasks[task_id]
    
    response_data = {
        'task_id': task_id,
        'status': task_info['status']
    }
    
    if task_info['status'] == 'processing':
        # 计算已处理时间
        elapsed_time = time.time() - task_info['start_time']
        response_data['elapsed_time'] = round(elapsed_time, 2)
    elif task_info['status'] == 'completed':
        response_data['result'] = task_info['result']
        response_data['processing_time'] = round(task_info['end_time'] - task_info['start_time'], 2)
    elif task_info['status'] == 'failed':
        response_data['error'] = task_info['error']
        response_data['processing_time'] = round(task_info['end_time'] - task_info['start_time'], 2)
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': response_data
    })


def add_comment_to_response(response_data: Dict[str, Any]) -> Dict[str, Any]:
    """为响应数据添加用户评价"""
    global comment_generator, salary_analyzer
    
    # 检查必要的组件是否存在
    if comment_generator is None or salary_analyzer is None:
        return response_data
    
    predicted_level = response_data.get('predicted_level')
    if not predicted_level:
        return response_data
    
    salary_range_text = "暂无薪资数据"
    if 'salary_analysis' in response_data and response_data['salary_analysis'].get('salary_range_found'):
        salary_range_text = response_data['salary_analysis'].get('salary_range_text', '暂无薪资数据')
    
    comment = comment_generator.generate_comment(predicted_level, salary_range_text)
    response_data['comment'] = comment
    
    return response_data


if __name__ == '__main__':
    # 启动时加载模型
    if not load_model():
        print("模型加载失败")
        sys.exit(1)
    
    print("职级预测API服务启动")
    
    # 启动Flask应用，增强并发处理能力
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=False,
        threaded=True,
        processes=1
    )
